package com.kmxd.ams.controller.oss;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kmxd.ams.client.oss.IOssAttachmentSvc;
import com.kmxd.ams.client.oss.dto.OssAttachmentQueryDTO;
import com.kmxd.ams.client.oss.dto.OssAttachmentUploadDTO;
import com.kmxd.ams.client.oss.vo.OssAttachmentListVO;
import com.kmxd.ams.client.oss.vo.OssAttachmentVO;
import com.kmxd.ams.core.common.constant.ErrorCode;
import com.kmxd.ams.core.common.enums.LogLevelEnum;
import com.kmxd.ams.core.common.enums.LogTypeEnum;
import com.kmxd.ams.core.exception.BizTipException;
import com.kmxd.ams.core.log.annotation.AutoLog;
import com.kmxd.ams.core.result.R;
import com.kmxd.ams.core.result.ResultCode;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 公共附件表 前端控制器
 *
 * @author ZuoLG
 * @since 2022-07-25
 */
@Slf4j
@RestController
@Tag(name = "公共附件表")
@RequestMapping("/oss/ossAttachment")
@AllArgsConstructor
public class OssAttachmentCtl {

  private IOssAttachmentSvc ossAttachmentService;

  /** 分页查询 */
  @Operation(summary = "分页查询")
  @GetMapping("/selectPage")
  @AutoLog(module = "公共附件表", type = LogTypeEnum.SYSTEM, level = LogLevelEnum.LOW, title = "分页查询")
  public R<Page<OssAttachmentListVO>> selectPage(Page reqPage, OssAttachmentQueryDTO req) {
    return R.success(ossAttachmentService.selectPage(reqPage, req));
  }

  /** 列表查询 */
  @Operation(summary = "列表查询")
  @GetMapping("/selectList")
  @AutoLog(module = "公共附件表", type = LogTypeEnum.SYSTEM, level = LogLevelEnum.LOW, title = "列表查询")
  public R<List<OssAttachmentListVO>> selectList(OssAttachmentQueryDTO req) {
    return R.success(ossAttachmentService.selectList(req));
  }

  @SneakyThrows
  @Operation(summary = "文件上传")
  @PostMapping("/upload")
  @AutoLog(module = "公共附件表", type = LogTypeEnum.SYSTEM, level = LogLevelEnum.HIGH, title = "文件上传")
  public R<OssAttachmentVO> upload(MultipartFile file, OssAttachmentUploadDTO req) {
    if (Objects.isNull(file)) {
      throw BizTipException.instance(ErrorCode.EXCEPTION, ResultCode.PARAM_MISS.getMessage());
    }
    return R.success(ossAttachmentService.upload(file, req));
  }

  /** 删除 */
  @Operation(summary = "删除")
  @PostMapping("/remove")
  @AutoLog(
      module = "公共附件表",
      type = LogTypeEnum.SYSTEM,
      level = LogLevelEnum.HIGH_RISK,
      title = "删除")
  public R<Void> remove(@RequestParam String ids) {
    ossAttachmentService.remove(ids);
    return R.success();
  }

  /** 查看 */
  @Operation(summary = "查看")
  @GetMapping("/view")
  @AutoLog(module = "公共附件表", type = LogTypeEnum.SYSTEM, level = LogLevelEnum.LOW, title = "查看")
  public R<OssAttachmentVO> view(@RequestParam Long id) {
    return R.success(ossAttachmentService.view(id));
  }

  /** 查看 */
  @Operation(summary = "查看文件流")
  @GetMapping("/show")
  @SneakyThrows
  @AutoLog(module = "公共附件表", type = LogTypeEnum.SYSTEM, level = LogLevelEnum.LOW, title = "查看文件流")
  public void show(@RequestParam Long id, HttpServletResponse response) {
    OssAttachmentVO view = ossAttachmentService.download(id);
    response.reset();
    try (ServletOutputStream out = response.getOutputStream()) {
      IoUtil.write(out, true, FileUtil.readBytes(view.getFile()));
    } catch (IOException e) {
      log.error("{} 文件下载失败", view, e);
    }
    }

  /** 文件下载 */
  @Operation(summary = "文件下载")
  @GetMapping("/download")
  @AutoLog(module = "文件下载", type = LogTypeEnum.SYSTEM, level = LogLevelEnum.HIGH, title = "文件下载")
  @SneakyThrows
  public void download(Long id, HttpServletResponse response) {
    OssAttachmentVO view = ossAttachmentService.download(id);
    response.reset();
    response.setContentType("application/octet-stream;charset=UTF-8");
    response.setCharacterEncoding("UTF-8");
    response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
    response.setHeader(
        "Content-Disposition",
        "attachment; filename="
            + URLEncoder.encode(view.getShowFileName(), StandardCharsets.UTF_8.name()));
    response.addHeader("Content-Length", String.valueOf(view.getFile().length()));
    try (ServletOutputStream out = response.getOutputStream()) {
      IoUtil.write(out, true, FileUtil.readBytes(view.getFile()));
    } catch (IOException e) {
      log.error("{} 文件下载失败", view, e);
    }
  }
  /** 文件预览 */
  @Operation(summary = "预览")
  @GetMapping("/preview")
  @AutoLog(module = "预览", type = LogTypeEnum.SYSTEM, level = LogLevelEnum.HIGH, title = "预览")
  @SneakyThrows
  public void preview(Long id, HttpServletResponse response) {
    OssAttachmentVO view = ossAttachmentService.preview(id);
    response.reset();
    response.setContentType("application/octet-stream;charset=UTF-8");
    response.setCharacterEncoding("UTF-8");
    response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
    response.setHeader(
        "Content-Disposition",
        "attachment; filename="
            + URLEncoder.encode(view.getShowFileName(), StandardCharsets.UTF_8.name()));
    response.addHeader("Content-Length", String.valueOf(view.getFile().length()));
    try (ServletOutputStream out = response.getOutputStream()) {
      IoUtil.write(out, true, FileUtil.readBytes(view.getFile()));
    } catch (IOException e) {
      log.error("{} 文件下载失败", view, e);
    }
  }
}
